/**
 * 坐骑基础表创建和数据导入脚本
 * 功能：创建mount_base表并导入坐骑基础数据
 */

const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库连接配置
const dbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs'
};

class MountTableManager {
    constructor() {
        this.connection = null;
    }

    // 建立数据库连接
    async connect () {
        try {
            this.connection = await mysql.createConnection(dbConfig);
            console.log('✅ 数据库连接成功');
        } catch (error) {
            console.error('❌ 数据库连接失败:', error.message);
            throw error;
        }
    }

    // 关闭数据库连接
    async disconnect () {
        if (this.connection) {
            await this.connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }

    // 创建坐骑基础表
    async createMountTable () {
        try {
            console.log('📋 开始创建坐骑基础表...');

            const createTableSQL = `
                CREATE TABLE IF NOT EXISTS mount_base (
                    id INT PRIMARY KEY COMMENT '坐骑ID',
                    name VARCHAR(100) NOT NULL COMMENT '坐骑名称',
                    descr VARCHAR(500) NOT NULL COMMENT '坐骑描述',
                    img VARCHAR(100) NOT NULL COMMENT '坐骑图片',
                    ap INT DEFAULT -1000 COMMENT '攻击力',
                    apIni INT DEFAULT -1000 COMMENT '初始攻击力',
                    hp INT DEFAULT -1000 COMMENT '生命值',
                    hpIni INT DEFAULT -1000 COMMENT '初始生命值',
                    mp INT DEFAULT -1000 COMMENT '法力值',
                    mpIni INT DEFAULT -1000 COMMENT '初始法力值',
                    sp INT DEFAULT -1000 COMMENT '速度',
                    spIni INT DEFAULT -1000 COMMENT '初始速度',
                    type TINYINT DEFAULT 1 COMMENT '坐骑类型：1-战马，2-名马，3-神马',
                    price INT DEFAULT 1980 COMMENT '坐骑价格',
                    createdAt DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                    updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='坐骑基础数据表';
            `;

            await this.connection.execute(createTableSQL);
            console.log('✅ 坐骑基础表创建成功');
        } catch (error) {
            console.error('❌ 创建坐骑基础表失败:', error.message);
            throw error;
        }
    }

    // 清空坐骑表数据
    async clearMountTable () {
        try {
            console.log('🗑️ 清空坐骑表数据...');
            await this.connection.execute('DELETE FROM mount_base');
            console.log('✅ 坐骑表数据已清空');
        } catch (error) {
            console.error('❌ 清空坐骑表数据失败:', error.message);
            throw error;
        }
    }

    // 导入坐骑数据
    async importMountData () {
        try {
            console.log('📥 开始导入坐骑数据...');

            // 读取坐骑基础数据JSON文件
            const dataPath = path.join(__dirname, 'output', '坐骑基础数据.json');

            if (!fs.existsSync(dataPath)) {
                throw new Error(`坐骑基础数据文件不存在: ${dataPath}`);
            }

            const mountData = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
            console.log(`📊 读取到 ${Object.keys(mountData).length} 条坐骑数据`);

            // 准备插入SQL
            const insertSQL = `
                INSERT INTO mount_base (
                    id, name, descr, img, ap, apIni, hp, hpIni, 
                    mp, mpIni, sp, spIni, type, price
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `;

            let successCount = 0;
            let errorCount = 0;

            // 批量插入数据
            for (const [id, mount] of Object.entries(mountData)) {
                try {
                    await this.connection.execute(insertSQL, [
                        parseInt(id),
                        mount.name,
                        mount.descr,
                        mount.img,
                        mount.ap,
                        mount.apIni,
                        mount.hp,
                        mount.hpIni,
                        mount.mp,
                        mount.mpIni,
                        mount.sp,
                        mount.spIni,
                        mount.type,
                        1980 // 默认价格
                    ]);
                    successCount++;
                    console.log(`✅ 导入坐骑: ${mount.name} (ID: ${id})`);
                } catch (error) {
                    errorCount++;
                    console.error(`❌ 导入坐骑失败 (ID: ${id}):`, error.message);
                }
            }

            console.log(`📊 导入完成统计:`);
            console.log(`   成功: ${successCount} 条`);
            console.log(`   失败: ${errorCount} 条`);
            console.log(`   总计: ${Object.keys(mountData).length} 条`);

        } catch (error) {
            console.error('❌ 导入坐骑数据失败:', error.message);
            throw error;
        }
    }

    // 验证导入结果
    async verifyImport () {
        try {
            console.log('🔍 验证导入结果...');

            const [rows] = await this.connection.execute('SELECT COUNT(*) as count FROM mount_base');
            const count = rows[0].count;

            console.log(`📊 坐骑表中共有 ${count} 条数据`);

            // 显示前几条数据作为示例
            const [sampleRows] = await this.connection.execute(
                'SELECT id, name, type FROM mount_base ORDER BY id LIMIT 5'
            );

            console.log('📋 前5条坐骑数据示例:');
            sampleRows.forEach(row => {
                console.log(`   ID: ${row.id}, 名称: ${row.name}, 类型: ${row.type}`);
            });

        } catch (error) {
            console.error('❌ 验证导入结果失败:', error.message);
            throw error;
        }
    }

    // 运行完整的表创建和数据导入流程
    async runFullProcess () {
        console.log('🚀 开始坐骑基础表创建和数据导入流程...\n');

        try {
            // 1. 连接数据库
            await this.connect();

            // 2. 创建表
            await this.createMountTable();

            // 3. 清空现有数据
            await this.clearMountTable();

            // 4. 导入数据
            await this.importMountData();

            // 5. 验证结果
            await this.verifyImport();

            console.log('\n🎉 坐骑基础表创建和数据导入完成！');

        } catch (error) {
            console.error('\n💥 流程执行失败:', error.message);
            throw error;
        } finally {
            // 6. 关闭连接
            await this.disconnect();
        }
    }
}

// 运行脚本
async function main () {
    console.log('🎯 坐骑基础表创建和数据导入脚本');
    console.log('   功能：创建mount_base表并导入坐骑基础数据\n');

    const manager = new MountTableManager();
    await manager.runFullProcess();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = MountTableManager;
